<?php

namespace App\Console\Commands;

use App\Models\BasicInfoPosition;
use App\Models\FormInstance;
use App\Models\FormInstanceBizRelation;
use Illuminate\Console\Command;

class UpdateBasicInfoPosition extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'AddVersionId:position';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步关联版本ID';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info("---同步,开始:".date('Y-m-d H:i:s')."---");
        $this->taskRun();
        // Log::channel('daily')->info('数据');
        $this->info("---同步,结束:".date('Y-m-d H:i:s')."---");
    }

    public function taskRun()
    {
        BasicInfoPosition::all()->chunk(200)->each(function($item, $key) {
            $item->each(function($position) {
                $biz = FormInstanceBizRelation::where('form_key', 'BASIC_POSITION_TABLE')
                    ->where('biz_id', $position->id)
                    ->first();
                    
                if($biz->data_version_id) {
                    BasicInfoPosition::whereId($position->id)->update(['data_version_id' => $biz->data_version_id]);
                } else {
                    $instance = FormInstance::whereId($biz->form_instance_id)->first();
                    BasicInfoPosition::whereId($position->id)->update(['data_version_id' => $instance->data_version_id]);
                }
            });
        });
    }
}
